import pandas as pd

df = pd.read_csv('static/data/farm_produce_pre.csv')
produce = df['产品代码'].unique()


def line_plot():
    data = [
        {
            'name': df[df['产品代码'] == i]['产品名称'].values.tolist()[0],
            'value': df[df['产品代码'] == i]['价格'].values.tolist(),
            'label': df[df['产品代码'] == i]['日期'].values.tolist()
        } for i in produce
    ]
    return {
        'data': data
    }


def pie_plot():
    data = df.drop_duplicates(subset=['产品代码']).groupby('产品规格')['产品名称'].count().reset_index().values.tolist()
    return {
        'data': [{'name': i[0], 'value': i[1]} for i in data],
    }


def bar_plot():
    change_rate_max = [
        [
            df[df['产品代码'] == i]['产品名称'].values[0],
            round((df[df['产品代码'] == i]['价格'].diff() / df[df['产品代码'] == i]['价格']).max(), 5)
        ] for i in produce
    ]
    df_rate_max = pd.DataFrame(change_rate_max, columns=['produce', 'change_rate_max'])
    data = df_rate_max.sort_values('change_rate_max', ascending=False).head(10).values.tolist()
    return {
        'label': [i[0] for i in data],
        'value': [round(i[1], 2) for i in data]
    }


def word_cloud_plot():
    data = df.groupby('产品名称')['产品代码'].count().reset_index().values.tolist()
    return {
        'data': [{'name': i[0], 'value': i[1]} for i in data]
    }


def boxplot_data():
    group = df[['产品名称', '价格']].groupby('产品名称')
    label = [i[0] for i in group]
    value = [[str(j[1]) for j in i[1].values] for i in group]
    return {
        'label': label,
        'value': value
    }


def mean_price_bar():
    data = df.groupby('产品名称')['价格'].mean().reset_index().values.tolist()
    return {
        'label': [i[0] for i in data],
        'value': [round(i[1], 2) for i in data]
    }
